﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace SuperX.Common.Helper
{
    /// <summary>
    /// 文件帮助工具
    /// </summary>    
    public static class FileUtil
    {
        /// <summary>
        /// 追加内容到指定文件中
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="content"></param>
        public static void WriteAppend(string filePath, string content)
        {
            FileUtil.WriteAppend(filePath, new string[]
            {
                content
            });
        }

        /// <summary>
        /// 追加内容到指定文件中
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="contents"></param>        
        public static void WriteAppend(string filePath, string[] contents)
        {
            using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
            {
                fileStream.Seek(fileStream.Length, SeekOrigin.Current);
                string s = string.Join(Environment.NewLine, contents) + Environment.NewLine;
                byte[] bytes = Encoding.UTF8.GetBytes(s);
                fileStream.Write(bytes, 0, bytes.Length);
                fileStream.Close();
            }
        }

        /// <summary>
        /// 10.7判断两个文件的哈希值是否一致
        /// </summary>
        /// <param name="fileName1"></param>
        /// <param name="fileName2"></param>
        /// <returns></returns>
        public static bool CompareFiles(string fileName1, string fileName2)
        {
            bool result;
            using (HashAlgorithm hashAlgorithm = HashAlgorithm.Create())
            {
                using (FileStream fileStream = new FileStream(fileName1, FileMode.Open))
                {
                    using (FileStream fileStream2 = new FileStream(fileName2, FileMode.Open))
                    {
                        byte[] value = hashAlgorithm.ComputeHash(fileStream);
                        byte[] value2 = hashAlgorithm.ComputeHash(fileStream2);
                        result = (BitConverter.ToString(value) == BitConverter.ToString(value2));
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="fullpath"></param>
        /// <returns></returns>
        public static bool IsExists(string fullpath)
        {
            return File.Exists(fullpath);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="fullpath"></param>
        public static void Delete(string fullpath)
        {
            if (File.Exists(fullpath))
            {
                File.Delete(fullpath);
            }
        }
    }
}
